import { InvKuCunOutput } from "/@/api/inv/InvKuCun";
import { InvTuiXueApi, InvTuiXueMingXiOutput, InvTuiXueOutput } from "/@/api/inv/InvTuiXue";
import { enumCode } from "/@/const";
import { loginInfo } from "/@/stores/baseInfo";
import { showError, showSuccess } from "/@/utils";
import { useConfirmDialog } from '/@/hooks/useConfirmDialog'


const initCtx = () => ({
  isEdit: true,
  loading: false,
  zhuBiao: { danJuLeiXing: '协议医院退血', tuiXueYiYuanId: loginInfo.value.yuanQuId, tuiXueYiYuan: loginInfo.value.yuanQuName } as InvTuiXueOutput,
  xueYeList: [] as InvKuCunOutput[],
  mingXiList: [] as InvTuiXueMingXiOutput[],
});

export const ctx = reactive(initCtx()); // 使用 reactive 初始化

export const billPanelRef = ref();
export const listRef = ref();
export const formRef = ref();

//#region 单据操作
/**
 * 新增
 */
export const newZhuBiao = () => {
  // 将上下文对象重置为初始状态
  Object.assign(ctx, initCtx());
  // 设置为编辑状态
  ctx.isEdit = true;
}
/**  */
export const loadEntity = (row) => {
  if (!row || !row.id) return;
  // 设置加载状态为 true
  ctx.loading = true;
  InvTuiXueApi.get(row.id).then(res => {
    ctx.isEdit = false;
    ctx.zhuBiao = res.zhuBiao;
    ctx.mingXiList = res.mingXiList;
    // 根据明细获取出血液列表信息
    ctx.xueYeList = res.mingXiList.map(item => item.xueYe);
  }).finally(() => {
    ctx.loading = false;
  })
}
export const submit = async () => {
  if (ctx.loading) return;
  const isVaild = await formRef.value?.validate();
  if (!isVaild) return;
  if (ctx.xueYeList.length == 0) {
    showError('请录入退血血液');
    return;
  }
  const param = {
    ...ctx.zhuBiao,
    mingXiList: ctx.xueYeList.map(item => ({ id: 0, invTuiXueId: '', xueYeId: item.id }))
  }
  ctx.loading = true;
  InvTuiXueApi.add(param).then(res => {
    showSuccess('保存成功');
    ctx.isEdit = false;
    loadEntity({ id: res });
  }).finally(() => {
    ctx.loading = false;
  })
}
/** 作废单据 */
export const cancel = () => {
  if (ctx.zhuBiao.danJuZhuangTai === enumCode.Djzt.待审核) {
    useConfirmDialog('确认作废吗?').then(async () => {
      await InvTuiXueApi.cancel({ id: ctx.zhuBiao.id });
      ctx.zhuBiao.danJuZhuangTai = enumCode.Djzt.已作废;
      showSuccess('已作废');
    });
  } else {
    showError('单据状态不是待审核，不能作废');
  }
}
//#endregion
//#region 明细操作
/**
 * 扫描血液信息并处理
 * @param blood 库存血液信息
 */
export const scanEnter = (blood: InvKuCunOutput) => {
  // 如果血液不在库中，则显示错误信息并返回
  if (blood.kuCunZhuangTai != enumCode.KuCunZhuangTai.在库) return showError('该血液不在库中');
  if (blood.laiYuanId != 1300000000001) return showError('该血液非协议医院入库血液');
  // 如果该血液已录入，则显示错误信息并返回
  if (ctx.xueYeList.find(item => item.id == blood.id)) return showError('该血液已录入');

  // 将扫描到的血液信息添加到快速发血明细列表中
  ctx.xueYeList.push(blood);
}
/**
 * 
 */
export const deleteBlood = (row: InvKuCunOutput) => {
  useConfirmDialog(`是否确认删除此数据`).then(() => {
    ctx.xueYeList = ctx.xueYeList.filter(item => item.id != row.id);
  })
}
//#endregion